package org.example.promptword.common;

import lombok.Data;
import org.springframework.stereotype.Component;

@Component
public class ColorGenerator {
    private static class HSLColor {
        private final float h;
        private final float s;
        private final float l;
        private int red, green, blue;

        public HSLColor(float h, float s, float l) {
            this.h = h;
            this.s = s;
            this.l = l;
            calculateRGB();
        }

        private void calculateRGB() {
            float c = (1 - Math.abs(2 * l / 100 - 1)) * s / 100;
            float x = c * (1 - Math.abs((h / 60) % 2 - 1));
            float m = l / 100 - c / 2;

            float r = 0, g = 0, b = 0;
            if (h < 60) {
                r = c; g = x; b = 0;
            } else if (h < 120) {
                r = x; g = c; b = 0;
            } else if (h < 180) {
                r = 0; g = c; b = x;
            } else if (h < 240) {
                r = 0; g = x; b = c;
            } else if (h < 300) {
                r = x; g = 0; b = c;
            } else {
                r = c; g = 0; b = x;
            }

            red = Math.round((r + m) * 255);
            green = Math.round((g + m) * 255);
            blue = Math.round((b + m) * 255);
        }

        public String toHex() {
            return String.format("#%02X%02X%02X", red, green, blue);
        }

        public String toRgba() {
            return String.format("rgba(%d, %d, %d, 0.1)", red, green, blue);
        }
    }

    private static final float GOLDEN_ANGLE = 137.508f;

    public ColorResult generateColorForTag(Integer tagId) {
        float hue = (tagId * GOLDEN_ANGLE) % 360;
        float saturation = 75f;
        float lightness = 55f;

        HSLColor hslColor = new HSLColor(hue, saturation, lightness);
        return new ColorResult(hslColor.toHex(), hslColor.toRgba());
    }

    @Data
    public static class ColorResult {
        private final String hexColor;
        private final String rgbaColor;

        public ColorResult(String hexColor, String rgbaColor) {
            this.hexColor = hexColor;
            this.rgbaColor = rgbaColor;
        }
    }
}